package at.jaki.ubb.crawling.demo.dataFinder;

import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import at.jaki.ubb.crawling.model.DataFinderResult;
import at.jaki.ubb.crawling.model.RawData;
import at.jaki.ubb.crawling.model.Target;
import at.jaki.ubb.crawling.stlib.dataFinder.SimpleHttpClient;
import at.jaki.ubb.crawling.stlib.utils.WebPageMinerUtils;

public class MediafaxSearcher extends SimpleHttpClient {

	private static final Logger LOG = Logger.getLogger(MediafaxSearcher.class);

	public static final String INPUT_TYPE = "mediafaxSearchInput";

	private static final String MEDIAFAX_SEARCH_PATH = "/cauta";
	private static final String MEDIAFAX_URL = "www.mediafax.ro";

	public DataFinderResult<String, String> findData(Target<String> t) {
		// http://www.mediafax.ro/cauta?q=planeta
		String url = null;
		try {
			url = WebPageMinerUtils.createURI(MEDIAFAX_URL, MEDIAFAX_SEARCH_PATH, getParams(t.getValue()));
			LOG.debug("Using URL " + url + " for translation");
		} catch (URISyntaxException e) {
			LOG.error(e);
			return new DataFinderResult<String, String>(null, null);
		}

		LOG.info("Getting page: " + url);

		String page = getPage(url);

		if (page != null) {
			RawData<String> rd = new RawData<String>(url, page, new Date(), RESULT_TYPE);
			Collection<RawData<String>> rawDataCollection = Collections.singletonList(rd);
			return new DataFinderResult<String, String>(rawDataCollection, null);
		} else {
			return new DataFinderResult<String, String>(null, null);
		}

	}

	private Map<String, String> getParams(String value) {
		Map<String, String> map = new HashMap<String, String>(1);
		map.put("q", value.trim());
		return map;
	}

	public void init() {
	}

	public Collection<String> getTypes() {
		return Collections.singletonList(INPUT_TYPE);
	}

}
